#pragma once

#include "Log.hpp"
#include "InetAddr.hpp"
#include <string>
#include <unordered_map>
#include <fstream>

using namespace logModule;

const std::string defaultDict = "./dictionary.txt";
const std::string separated = ":";

class DictServer
{
public:

    DictServer(const std::string& dict_path = defaultDict)
        :_dict_path(dict_path)
    {
        ;
    }

    bool getWords()
    {
        std::ifstream in(_dict_path);
        if (in.is_open() == false)
        {
            LOG(LogLevel::WARNING) << "dict getWords failure";
            return false;
        }
        
        std::string line;
        while (std::getline(in, line))
        {
            auto pos = line.find(separated);
            if (pos == line.npos)
            {
                if (line.empty())
                {
                    LOG(LogLevel::WARNING) << "get word blank line";
                }
                else
                {
                    LOG(LogLevel::WARNING) << "get word [" << line << "] failure";
                }
                continue;
            }

            std::string english = line.substr(0, pos);
            std::string chinese = line.substr(pos + 1);
            if (english.empty() || chinese.empty())
            {
                LOG(LogLevel::WARNING) << "get word [" << english << ":" << chinese << "] failure";
                continue;
            }

            _dict.emplace(std::move(english), std::move(chinese));
        }
    }

    std::string translate(const std::string& word, const InetAddr& client)
    {
        auto pos = _dict.find(word);
        std::string ans;
        if (pos == _dict.end())
        {
            ans = "翻译不存在";
        }
        else
        {
            ans = pos->second;
        }

        LOG(LogLevel::DEBUG) << "[" << client.getIp() << ":" << client.getPort() 
        << "] translate {" << word << ":" << ans << "}";

        return std::move(ans);
    }

    ~DictServer()
    {
        ;
    }

private:

    std::string _dict_path;
    std::unordered_map<std::string, std::string> _dict;
    
};